<template>
  <div class="channel-edit">
    <van-cell :border="false">
      <div slot="title" class="title-text">我的频道</div>
      <van-button
        class="edit-btn"
        type="danger"
        plain
        round
        size="mini"
        @click="isEdit = !isEdit"
        >{{ isEdit ? '完成' : '编辑' }}</van-button
      >
    </van-cell>
    <van-grid class="my-grid" :gutter="10">
      <van-grid-item
        class="grid-item"
        v-for="(channel, index) in myChannels"
        :key="index"
        @click="onMyChannelClick(channel, index)"
      >
        <van-icon
          v-show="isEdit && !fiexdChannels.includes(channel.id)"
          slot="icon"
          name="clear"
        ></van-icon>
        <span slot="text" :class="{ active: index === active }" class="text">{{
          channel.name
        }}</span>
      </van-grid-item>
    </van-grid>

    <!-- 频道推荐 -->
    <van-cell :border="false">
      <div slot="title" class="title-text">频道推荐</div>
    </van-cell>
    <van-grid class="recommend-grid" :gutter="10">
      <van-grid-item
        class="grid-item"
        v-for="(item, index) in recommendChannels"
        :key="index"
        :text="item.name"
        icon="plus"
        @click="onAddChannel(item)"
      />
    </van-grid>
  </div>
</template>

<script>
import {
  getAllChannels,
  addUserChannel,
  deleteUserChannel,
} from '@/api/channel'
import { mapState } from 'vuex'
import { setItem } from '@/utils/storage'

export default {
  name: 'ChannelEdit',
  components: {},
  props: {
    myChannels: {
      type: Array,
      required: true,
    },
    active: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      // 所有频道列表
      allChanels: [],
      // 控制编辑状态的显示
      isEdit: false,
      // 固定频道 不允许删除
      fiexdChannels: [0],
    }
  },
  computed: {
    // 映射vuex中的user
    ...mapState(['user']),

    recommendChannels() {
      return this.allChanels.filter((channels) => {
        return !this.myChannels.find((myChannels) => {
          return myChannels.id === channels.id
        })
      })
    },
  },
  watch: {},
  created() {
    this.loadAllChannels()
  },
  mounted() {},
  methods: {
    async loadAllChannels() {
      try {
        const { data } = await getAllChannels()
        this.allChanels = data.data.channels
        // console.log(data)
      } catch (err) {
        // console.log(err)
        this.$toast('数据获取失败！')
      }
    },

    async onAddChannel(channel) {
      this.myChannels.push(channel)

      // 数据持久话处理
      if (this.user) {
        // 已登录把数据存到后台
        try {
          await addUserChannel({
            id: channel.id,
            seq: this.myChannels.length,
          })
        } catch (error) {
          this.$toast('保存失败，请稍后重试')
        }
      } else {
        // 未登录则把数据存储到本地
        setItem('TOUTIAO_CHANNELS', this.myChannels)
      }
    },

    onMyChannelClick(channel, index) {
      // console.log(channel, index)
      // 如果是固定频道 则不允许删除
      if (this.isEdit) {
        if (this.fiexdChannels.includes(channel.id)) {
          return
        }
        // 删除频道项
        this.myChannels.splice(index, 1)
        // 如果删除的是激活频道之前或者它本身 则需要更新激活的频道项
        if (index <= this.active) {
          // 编辑状态
          this.$emit('updata-active', this.active - 1, true)
        }

        // 持久化处理
        this.deleteChannel(channel)
      } else {
        // 非编辑状态
        this.$emit('updata-active', index, false)
      }
    },

    async deleteChannel(channel) {
      if (this.user) {
        // 已登录
        try {
          await deleteUserChannel(channel.id)
        } catch (error) {
          this.$toast('删除失败')
        }
      } else {
        // 未登录
        setItem('TOUTIAO_CHANNELS', this.myChannels)
      }
    },
  },
}
</script>
<style lang='less' scoped>
.channel-edit {
  padding-top: 85px;

  .title-text {
    font-size: 32px;
    color: #333;
  }

  .edit-btn {
    width: 104px;
    height: 48px;
    font-size: 26px;
    color: #f85959;
    border: 1px solid #f85959;
  }

  .grid-item {
    width: 160px;
    height: 86px;
    /deep/.van-grid-item__content {
      background-color: #f4f5f6;
      .van-grid-item__text,
      .text {
        font-size: 28px;
        color: #222;
        margin-top: unset;
      }
      .active {
        color: red;
      }
      .van-grid-item__icon-wrapper {
        position: unset;
      }
    }
  }

  /deep/ .recommend-grid {
    .grid-item {
      .van-grid-item__content {
        flex-direction: row;
        white-space: nowrap;
        .van-icon-plus {
          font-size: 28px;
          margin-right: 6px;
        }
      }
    }
  }

  /deep/.my-grid {
    .grid-item {
      .van-icon-clear {
        position: absolute;
        right: -10px;
        top: -10px;
        font-size: 30px;
        color: #cacaca;
        z-index: 2;
      }
    }
  }
}
</style>
